import logging
import logging.handlers
import zmail


class BufferingSMTPHandler(logging.handlers.BufferingHandler):
    def __init__(self, fromaddr, toaddrs, subject, capacity=1000):
        logging.handlers.BufferingHandler.__init__(self, capacity)
        self.fromaddr = fromaddr
        self.toaddrs = toaddrs
        self.subject = subject
        self.setFormatter(logging.Formatter("%(asctime)s %(levelname)-5s %(message)s"))
        self.server = zmail.server('ruangnazi@163.com', 'JSBIRLXKWMBMHOXN')

    def flush(self):
        if len(self.buffer) > 0:
            try:
                msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nIncluded messages: %s\r\n\r\n" % (self.fromaddr, ",".join(self.toaddrs), self.subject,len(self.buffer))
                for record in self.buffer:
                    s = self.format(record)
                    msg = msg + s + "\r\n"
                mail = {
                    'subject': self.subject,
                    'content_text': msg
                }
                self.server.send_mail(['lu.hongfei@shuzhi.ai'],mail)
            except:
                # self.handleError()  # no particular record
                pass
            self.buffer = []


# # LogFormatter = logging.Formatter("%(asctime)s - %(levelname)s -  %(message)s")
# LogFormatter = logging.Formatter("%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s")

